package acm.LoginController;
/**
 * @author Emporeo
 * @web http://www.fai-communication.de/accountManager
 * @web source: http://code.google.com/p/mmo-account-manager/
 */
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import acm.account.l2j.Account_L2J;

public class LoginController extends HttpServlet{
	private static final long serialVersionUID = 1L;
	private HttpServletRequest request;
	private HttpServletResponse response;
	
	protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1)
	throws ServletException, IOException {
	
//	Datenfelder initialisieren
	this.request = arg0;
	this.response = arg1;
	
//	Kontext holen
	ServletContext context = request.getSession().getServletContext();
	
	context.log("LOGIN: " + request.getRemoteAddr());
	
	String login = request.getParameter("login");
	String password = request.getParameter("password");
	String account_for_game = request.getParameter("ACCOUNT_FOR_GAME");
	
	if((login.trim().toLowerCase().equals("")) || (password.trim().equals("")) ){
//		send back to login page
		String error = "Please, enter your login and password.";
		request.getSession().setAttribute("FRONT_LOGIN_ERROR", error);
		response.sendRedirect(response.encodeURL(request.getContextPath()+"/index.jsp"));
	}else{
		if(account_for_game.equals("L2J")){
			Account_L2J account = new Account_L2J(context);
			if(account.isLoginValid(login, password)){
				//valid login
				request.getSession().setAttribute("FRONT_LOGIN_NAME", login);
				request.getSession().setAttribute("ACCOUNT_FOR_GAME", account_for_game);
				response.sendRedirect(response.encodeURL(request.getContextPath()+"/account/index.jsp"));
			}else{
//				send back to login page
				String error = "Game account does not exist, or password wrong";
				request.getSession().setAttribute("FRONT_LOGIN_ERROR", error);
				response.sendRedirect(response.encodeURL(request.getContextPath()+"/index.jsp"));
			}
		}else if(account_for_game.equals("AION-EMU")){
			//TODO
		}else{
//			send back to login page
			String error = "Game account not valid.";
			request.getSession().setAttribute("FRONT_LOGIN_ERROR", error);
			response.sendRedirect(response.encodeURL(request.getContextPath()+"/index.jsp"));
		}
		}
		
	}//End Post
	
}//End Class
